<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>放大镜</title>
    <link rel="stylesheet" href="./css/magnifier.css">
</head>

<body>
    <div class="container">
        <img src="./img/2233.jpg" alt="">
        <div class="move">
            <img src="./img/2233.jpg" alt="">
        </div>
    </div>
    <script>
        const container = document.querySelector('.container')
        const move = document.querySelector('.move')
        const bigImg = document.querySelector('.move img')
        container.addEventListener('mouseover',function(e){
            move.classList.remove('hidden')
        })
        container.addEventListener('mouseout',function(e){
            move.classList.add('hidden')
        })
        //绑定containter的鼠标移动事件
        container.addEventListener('mousemove', function (e) {
            //获取鼠标距离左边的偏移
            let x = e.clientX;
            //获取container.offsetLeft
            let l = container.offsetLeft
            //计算最终的left值
            let moveLeft = x - l - move.offsetWidth / 2
            if (moveLeft <= 0) moveLeft = 0
            let maxLeft = container.offsetWidth - move.offsetWidth
            if (moveLeft >= maxLeft) moveLeft = maxLeft
            let bigImgLeft = (moveLeft + move.offsetWidth / 2) / container.offsetWidth * bigImg.offsetWidth
            //bigImg.style.left = -bigImgLeft + 'px'
            ////////////
            //获取鼠标距离上边的偏移
            let y = e.clientY;
            //获取container.offsetLeft
            let t = container.offsetTop
            //计算最终的left值
            let moveTop = y - t - move.offsetHeight / 2
            if (moveTop <= 0) moveTop = 0
            let maxTop= container.offsetHeight - move.offsetHeight
            if (moveTop >= maxTop) moveTop = maxTop
            let bigImgTop = (moveTop + move.offsetHeight / 2) / container.offsetHeight * bigImg.offsetHeight
            
            bigImg.style.top = -bigImgTop + 'px'
            bigImg.style.left = -bigImgLeft + 'px'

            move.style.top = moveTop + 'px'
            move.style.left = moveLeft + 'px'
        })
    </script>
</body>

</html>